package cn.dida.dao;

import cn.dida.model.stastic.ProductScanCountByDate;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 扫码统计 数据交互类
 * @author weiwei
 */
@Repository
public class StasticDao extends DaoBase {

	/**
	 * 商品扫码量统计
	 * @param companyId 公司id
	 * @param keyword 查询条件:商品名称\编号 \条码
	 * @param timeLimitStart 扫码开始时间
	 * @param timeLimitEnd 扫码结束时间
	 * @param page 分页游标
	 * @return Map<Integer, ArrayList<ProductScanCountByDate>> 商品扫码量
	 */
    public Map<Integer, ArrayList<ProductScanCountByDate>> stasticProductScanCountByDate(Integer companyId, String keyword, Long timeLimitStart, Long timeLimitEnd, int page) {


        //step1:查询出符合筛选条件的商品ID

        Object[] step1_args = {};
        StringBuffer sqlQueryResult = new StringBuffer("select t3.id,t3.`name` as pname from log_scan_qrcode t1 join qrcode_detail_"+companyId+" t2 on t1.uuid = t2.uuid join product t3 on t2.product_id = t3.id");


        StringBuffer step1_sqlWhere = new StringBuffer(" where t3.state=1 and t3.company_id = ?");
        step1_args = ArrayUtils.add(step1_args, companyId);
        if (StringUtils.isNotBlank(keyword)) {
            step1_sqlWhere.append(" and (t3.name  like ? or t3.barcode = ? or t3.number = ?)");
            step1_args = ArrayUtils.add(step1_args, "%" + keyword + "%");
            step1_args = ArrayUtils.add(step1_args, keyword);
            step1_args = ArrayUtils.add(step1_args, keyword);
        }

        // 查询记录
        sqlQueryResult.append(step1_sqlWhere).append(" group by t3.id limit ?,?");
        step1_args = ArrayUtils.add(step1_args, (page - 1) * getPageSize());
        step1_args = ArrayUtils.add(step1_args, getPageSize());
        List<Map<String,Object>> filterProductIdList = jdbcTemplate.queryForList(sqlQueryResult.toString(), step1_args);


        //step2:统计
        Object[] step2_args = {};
        StringBuffer sqlStastic = new StringBuffer("select t1.scan_time scanDate, t3.id 'product_id',t3.name 'product_name',count(1) 'scanCount' from log_scan_qrcode t1 join qrcode_detail_"+companyId+" t2 on t1.uuid = t2.uuid join product t3 on t2.product_id = t3.id");
        StringBuffer step2_sqlWhere = new StringBuffer(" where t3.company_id = ?");
        step2_args = ArrayUtils.add(step2_args, companyId);


        if (timeLimitStart != null) {
            step2_sqlWhere.append(" and t1.scan_time >= ?");
            step2_args = ArrayUtils.add(step2_args, timeLimitStart);
        }
        if (timeLimitEnd != null) {
            step2_sqlWhere.append(" and t1.scan_time <= ?");
            step2_args = ArrayUtils.add(step2_args, timeLimitEnd);
        }

        if (!CollectionUtils.isEmpty(filterProductIdList)) {
            step2_sqlWhere.append(" and t3.id in (");
            for (int i = 0; i < filterProductIdList.size(); i++) {
            	Map<String,Object> map = filterProductIdList.get(i);
                Integer productId = (Integer) map.get("id");
                step2_sqlWhere.append("?");
                step2_args = ArrayUtils.add(step2_args, productId);
                if (i < filterProductIdList.size() - 1) {
                    step2_sqlWhere.append(",");
                }
            }
            step2_sqlWhere.append(")");
        }

        // 查询统计数据
        List<ProductScanCountByDate> result = jdbcTemplate.query(sqlStastic.append(step2_sqlWhere).append(" group by FROM_UNIXTIME(t1.scan_time/1000, '%Y%m%d') order by t1.scan_time").toString(), step2_args, new BeanPropertyRowMapper<>(ProductScanCountByDate.class));
        Map<Integer, ArrayList<ProductScanCountByDate>> wrappedResult = new HashMap<>();
        if(CollectionUtils.isEmpty(result) && !CollectionUtils.isEmpty(filterProductIdList)){
        	  Calendar startDate = Calendar.getInstance();
              startDate.clear();
              Calendar endDate = Calendar.getInstance();
              endDate.clear();
              Calendar mindate = Calendar.getInstance();
              mindate.setTimeInMillis(timeLimitStart);
              startDate.set(mindate.get(Calendar.YEAR), mindate.get(Calendar.MONTH), mindate.get(Calendar.DATE));
              Calendar maxdate = Calendar.getInstance();
              maxdate.setTimeInMillis(timeLimitEnd);
              endDate.set(maxdate.get(Calendar.YEAR), maxdate.get(Calendar.MONTH), maxdate.get(Calendar.DATE)+1);
        	
              Long daylong = 86400000L;
              
              for(Map<String,Object> pmap: filterProductIdList){
            	    ArrayList<ProductScanCountByDate> productScanCountByDateList = new ArrayList<ProductScanCountByDate>();
            	    Integer pid = (Integer) pmap.get("id");
                    for (int i = 0; i < (endDate.getTimeInMillis() - startDate.getTimeInMillis()) / (1000 * 3600 * 24); i++) {
                    	
                        ProductScanCountByDate tmp = new ProductScanCountByDate();
                        tmp.setScanCount(0l);
                        tmp.setProductId(pid);
                        tmp.setProductName("此查询条件内无满足的扫码统计数据");
                        Long tl = startDate.getTimeInMillis() + (daylong * i);
                        tmp.setScanDate(tl);
                        productScanCountByDateList.add(tmp);
                    }
                    wrappedResult.put(pid, productScanCountByDateList);
                    break;
              }
              
          
        	
        }
        
        
        
        if (!CollectionUtils.isEmpty(result) && !CollectionUtils.isEmpty(filterProductIdList)) {
            //补全缺省数据
            Calendar startDate = Calendar.getInstance();
            startDate.clear();
            Calendar endDate = Calendar.getInstance();
            endDate.clear();

            Calendar mindate = Calendar.getInstance();
            //mindate.setTimeInMillis(result.get(0).getScanDate());
            mindate.setTimeInMillis(timeLimitStart);
            startDate.set(mindate.get(Calendar.YEAR), mindate.get(Calendar.MONTH), mindate.get(Calendar.DATE));
            Calendar maxdate = Calendar.getInstance();
            //maxdate.setTimeInMillis(result.get(result.size() - 1).getScanDate());
            maxdate.setTimeInMillis(timeLimitEnd);
            endDate.set(maxdate.get(Calendar.YEAR), maxdate.get(Calendar.MONTH), maxdate.get(Calendar.DATE)+1);
            
            
            Long daylong = 86400000L;
            
            for (ProductScanCountByDate productScanCountByDate : result) {
                ArrayList<ProductScanCountByDate> productScanCountByDateList = wrappedResult.get(productScanCountByDate.getProductId());

                if (productScanCountByDateList == null) {
                    productScanCountByDateList = new ArrayList<>();
                    Integer ln = (int) ((endDate.getTimeInMillis() - startDate.getTimeInMillis()) / (1000 * 3600 * 24));
                    for (int i = 0; i < ln; i++) {
                        ProductScanCountByDate tmp = new ProductScanCountByDate();
                        tmp.setScanCount(0l);
                        tmp.setProductId(productScanCountByDate.getProductId());
                        tmp.setProductName(productScanCountByDate.getProductName());
                        Long tl = startDate.getTimeInMillis() + (daylong * i);
                        tmp.setScanDate(tl);
                        productScanCountByDateList.add(tmp);
                    }
                    wrappedResult.put(productScanCountByDate.getProductId(), productScanCountByDateList);
                }


                for (int i = 0; i < productScanCountByDateList.size(); i++) {
                    ProductScanCountByDate tmp = productScanCountByDateList.get(i);
                    Calendar defaultPoint = Calendar.getInstance();
                    defaultPoint.setTimeInMillis(tmp.getScanDate());

                    Calendar dataPoint = Calendar.getInstance();
                    dataPoint.setTimeInMillis(productScanCountByDate.getScanDate());

                    Calendar reset = Calendar.getInstance();
                    reset.clear();
                    reset.set(dataPoint.get(Calendar.YEAR), dataPoint.get(Calendar.MONTH), dataPoint.get(Calendar.DATE));

                    if (reset.compareTo(defaultPoint) == 0) {
                        productScanCountByDateList.set(i, productScanCountByDate);
                    }
                }
            }
        }

        //按时间排序
//        for (ArrayList<ProductScanCountByDate> productScanCountByDates : wrappedResult.values()) {
//            Collections.sort(productScanCountByDates, new Comparator<ProductScanCountByDate>() {
//                @Override
//                public int compare(ProductScanCountByDate o1, ProductScanCountByDate o2) {
//                    return o2.getScanDate().compareTo(o2.getScanDate());
//                }
//
//            });
//        }

		
/*		for(Integer key : wrappedResult.keySet()){
			ArrayList<ProductScanCountByDate> list = wrappedResult.get(key);
			for(ProductScanCountByDate p : list){
				System.out.println("key:"+key+";pname:"+p);
			}
		}*/

        return wrappedResult;
    }
}
